<script setup lang="ts">
import {reactive, ref, onBeforeMount, nextTick} from "vue";
import {useRouter} from "vue-router";
import tableList from "@/components/tableList/tableList.vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {userList, userDelete, userUpdate, userInsert} from "@/api/system/user";

const router = useRouter()
let tableData = ref()
const searchRef = ref('')
const passRef = ref('')
const accountVisible = ref(false)
const loading = ref(false)
const subLoading = ref(false)
const pageData = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0,
})

const formInline = reactive({
  name: '',
  exam_num: ''
})

const accountForm = reactive({
  id: '',
  name: '',
  idnum: '',
  exam_num: '',
  is_admin: '0',
  started_at:'',
})

const rules = {
  name: [{required: true, message: '请输入姓名',}],
  idnum:[{required: true, message: '请输入身份证号码',}],
  exam_num: [{required: true, message: '请输入准考证号',}],
  is_admin: [{required: true, message: '请选择身份', trigger: 'change'}],
  started_at: [{required: true, message: '请选择考试时间', trigger: 'change'}],
}

const tableHeader = reactive([
  {label: '姓名', prop: 'name',width: '150px'},
  {label: '身份证号', prop: 'idnum',width:'190px'},
  {label: '准考证号', prop: 'exam_num'},
  {
    label: '身份', prop: 'is_admin', width: '80px', type: 'html', code: (row) => {
      if (row.is_admin === '1') {
        return '管理员'
      } else {
        return '学生'
      }
    }
  },
  {label: '考试时间', prop: 'started_at'},
  {label: '创建时间', prop: 'created_at'},
])

const tableOptions = reactive(
    {
      label: '操作',
      width: '180px',
      value: 1,
      options: [
        {
          label: '编辑',
          icon: 'Edit',
          method: (row) => {
            handleEdit(row)
          }
        },
        {
          label: '删除',
          icon: 'Delete',
          method: (row) => {
            handleDelete(row)
          }
        },
      ]
    }
)

const handleEdit = (row) => {
  accountVisible.value = true
  nextTick(()=>{
    Object.assign(accountForm, row)
  })
}

const handleDelete = (row)=>{
  ElMessageBox.confirm('是否删除该账号,一旦删除无法恢复', '提示', {type: 'warning'}).then(async () => {
      let res = await userDelete({id:row.id});
      if (res) {
        ElMessage({message: '删除成功', type: 'success'})
        await fetchData();
      }

  }).catch(() => {
  })
}

const handleSave = async () => {
  passRef.value.validate(async (valid) => {
    if (valid) {
      let res = {}
      subLoading.value = true
      if (accountForm.id) {
        res = await userUpdate(accountForm)
      } else {
        res = await userInsert(accountForm)
      }
      subLoading.value = false
      if (res) {
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
        handleClose()
       await fetchData()
      }
    }
  })
}
const onSearch = () => {
  pageData.currentPage = 1
  fetchData()
}

const handleReset = () => {
  searchRef.value.resetFields()
}

const handlePageChange = (param) => {
  pageData.pageSize = param.limit
  pageData.currentPage = param.page
  fetchData()
}


const fetchData = async () => {
  let params = formInline
  params.page = pageData.currentPage
  params.limit = pageData.pageSize
  loading.value = true
  let res = await userList(params);
  console.log('user', res)
  loading.value = false
  if (res) {
    tableData.value = res.data.list
    pageData.total = res.data.page.amount
  }
}

const onAdd = () => {
  accountVisible.value = true
}

const handleClose = () => {
  accountForm.id = ''
  nextTick(()=>{
    passRef.value.resetFields();
  })
  accountVisible.value = false
}

onBeforeMount(() => {
  fetchData()
})

</script>
<template>
  <el-row :justify="'center'">
    <el-col :span="18" :xs="24">
      <el-form :inline="true" :model="formInline" class="el-input-form" ref="searchRef">
        <el-form-item label="姓名" prop="name">
          <el-input @keyup.enter="fetchData()" v-model="formInline.name" placeholder="姓名" clearable/>
        </el-form-item>
        <el-form-item label="准考证号" prop="exam_num">
          <el-input @keyup.enter="fetchData()" v-model="formInline.exam_num" placeholder="准考证号" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="onSearch" clearable icon="search">查询</el-button>
          <el-button plain @click="handleReset" icon="RefreshLeft">重置</el-button>
          <el-button @click="onAdd" icon="plus">添加账号</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <el-col :span="18" :xs="24" class="white-shadow" v-loading="loading">
      <tableList :table-data="tableData"
                 :table-header="tableHeader"
                 :page-data="pageData"
                 @handlePageChange="handlePageChange"
                 :table-options="tableOptions">
      </tableList>
    </el-col>
  </el-row>
  <el-dialog v-model="accountVisible" :title="accountForm.id ?'编辑账号':'添加账号'" draggable width="40%"
             :before-close="handleClose">
    <el-row justify="center">
      <el-col :span="20">
        <el-form label-width="80px" ref="passRef" :rules="rules" :model="accountForm">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="accountForm.name"  placeholder="请输入考生姓名"/>
          </el-form-item>
          <el-form-item label="身份证号" prop="idnum">
            <el-input v-model="accountForm.idnum" placeholder="请输入考生身份证号码"/>
          </el-form-item>
          <el-form-item label="准考证号" prop="exam_num">
            <el-input v-model="accountForm.exam_num" placeholder="请输入考生准考证号"/>
          </el-form-item>
          <el-form-item label="身份" prop="is_admin" >
            <el-select v-model="accountForm.is_admin" style="width: 100%;"  @change="accountForm.started_at =''"  placeholder="请输入身份">
              <el-option label="学生" value="0"></el-option>
              <el-option label="管理员" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="考试时间" prop="started_at" v-if="accountForm.is_admin === '0'">
            <el-date-picker
                style="width: 100%"
                type="datetime"
                v-model="accountForm.started_at"
                format="YYYY-MM-DD HH:mm"
                placeholder="请输入考生考试开始时间"
                value-format="YYYY-MM-DD HH:mm"
            />
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleSave" :loading="subLoading">保存</el-button>
        <el-button @click="handleClose">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>


